package com.yc.algorithm.leetcode;

import com.yc.algorithm.leetcode.singleList.ListNode;
import com.yc.algorithm.sort.SortDemo;

/**
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 * 示例1
 * 输入：l1 = [1,2,4], l2 = [1,3,4]
 * 输出：[1,1,2,3,4,4]
 * 示例2
 * 输入：l1 = [], l2 = []
 * 输出：[]
 * 示例3
 * 输入：l1 = [], l2 = [0]
 * 输出：[0]
 */
public class MergeTwoLists {


    public static void main(String[] args) {
        MergeTwoLists mergeTwoLists = new MergeTwoLists();
        ListNode l1 = new ListNode(1);
        ListNode l1_1 = new ListNode(2);
        ListNode l1_2 = new ListNode(4);
//        ListNode l1_3 = new ListNode();
//        ListNode l1_4 = new ListNode();
        l1.next = l1_1;
        l1_1.next = l1_2;

        ListNode l2 = new ListNode(1);
        ListNode l2_1 = new ListNode(3);
        ListNode l2_2 = new ListNode(4);
        l2.next = l2_1;
        l2_1.next = l2_2;
        ListNode mergeListNode = mergeTwoLists.solution(l1, l2);
        do {
            System.out.println(mergeListNode.val);
        } while ((mergeListNode =mergeListNode.next) != null);
    }

    public ListNode solution(ListNode l1, ListNode l2) {
        // 获取两个链表的长度
        // 建立一个数组，长度和两个链表的和
        // 初始化数组
        // 对数组做排序
        if (l1 == null && l2 == null) {
            return null;
        }
        int size1 = 0;
        int size2 = 0;

        ListNode temp1 = l1;
        ListNode temp2 = l2;

        do {
            size1 ++;
        } while((temp1 = temp1.next) != null);
        do {
            size2 ++;
        } while((temp2 = temp2.next) != null);

        int[] nodeArr = new int[size1 + size2];
        int sizeTemp = 0;
        do {
            nodeArr[sizeTemp++] = l1.val;
        } while((l1 = l1.next) != null);

        do {
            nodeArr[sizeTemp++] = l2.val;
        } while ((l2 = l2.next) != null);

        SortDemo sortDemo = new SortDemo();
        sortDemo.bubbleSort(nodeArr);
        ListNode result = new ListNode();
        result.val = nodeArr[0];
        ListNode node = result;
        for (int i=1; i<nodeArr.length; i++) {
            ListNode temp = new ListNode(nodeArr[i]);
            node.next = temp;
            node = node.next;
        }
        return result;
    }



    static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) {
            this.val = val;
        }
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
